<?php
namespace App\Http\Controllers\Dashboard;

use App\Events\AllocateEvent;
use App\Events\LoanTagEvent;
use App\Events\Ticket\ConsumeEvent;
use App\Events\Ticket\RefundEvent;
use App\Events\UpdateEvent;
use App\Http\Controllers\Common\Internal;
use App\Models\LoanApplication;
use App\Models\LoanApplicationLog;
use App\Models\LoanTag;
use App\Models\Org;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class LoanController extends BaseController
{

    /**
     * 贷款物料列表
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request) {

        $pageSize = (int) $request->input('pageSize', 20);
        $query = LoanApplication::ofOwner($request->user())->with(['org','user'])->orderByDesc('id');

        if ($orgCode = $request->org_code) {
            $query->where('org_code', $orgCode);
        }

        if ($category = $request->category) {
            $query->where('category', $category);
        }
        if ($number = $request->number) {
            $query->where('number', 'like', "%{$number}%");
        }
        if ($status = $request->status) {
            if($status == 'have'){
                $query->where('user_id','!=',0);
            }
            if($status == 'not-have'){
                $query->where('user_id',0);
            }
            if($status == 'refund'){
                $query->whereIn('status',[15,16,17]);
            }
            if($status == 'error'){
                $query->whereIn('status',[7,8,9,10,11,12,14]);
            }
        }
        if ($custom_field = $request->custom_field) {
            $query->where('custom_field', 'like', "%{$custom_field}%");
        }
        if ($user_id = $request->user_id) {
            $query->where('user_id', $user_id);
        }


        if ($queryCity = $request->input('city')) {
            $query->where(function ($query) use($queryCity) {
                $query->where('province', 'like', "%{$queryCity}%")
                    ->orwhere('city', 'like', "%{$queryCity}%")
                    ->orwhere('district', 'like', "%{$queryCity}%")
                    ->orwhere('addr', 'like', "%{$queryCity}%");
            });
        }

        if ($queryName = $request->input('name')) {
            $query->where('name', 'like', "%{$queryName}%");
        }

        if ($queryMobile = $request->input('mobile')) {
            $query->where('mobile', 'like', "%{$queryMobile}%");
        }

        $data = $query->paginate($pageSize);

        foreach ($data as $value){
            $value->need_ticket = Internal::getNeedTicket($value->category_type, $value->province,$value->id);
            $value->status_name = Internal::getStatusName($value->status);
        }


        return response()->json($data);
    }


    /**
     * 物料分派
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function allocate(Request $request)
    {
        if (empty($request->loan_ids) || (empty($request->org_id) && empty($request->user_id))) {
            return response()->json([
                'code' => 1,
                'msg' => '参数不完整',
                'data' => null
            ]);
        }

        if ($request->org_id) {
            $org = Org::ofOrgCode($request->user())->find($request->org_id);
            if (empty($org)) {
                return response()->json([
                    'code' => 1,
                    'msg' => '没有部门数据权限',
                    'data' => null
                ]);
            }
        }

        if ($request->user_id) {
            $user = User::ofOrgCode($request->user())->find($request->user_id);
            if (empty($user)) {
                return response()->json([
                    'code' => 1,
                    'msg' => '没有员工数据权限',
                    'data' => null
                ]);
            }
        }

        $success = 0;
        foreach ($request->loan_ids as $load_id) {
            $loan = LoanApplication::ofOwner($request->user())->find($load_id);
            if (empty($loan)) {
                return response()->json([
                    'code' => 1,
                    'msg' => '没有数据权限',
                    'data' => null
                ]);
            }
            if ($request->user_id) {
                $loan->is_allocated = 1;
                $loan->org_root = $user->org_root;
                $loan->org_code = $user->org_code;
                $loan->user_id = $user->id;
            } else if ($request->org_id)  {
                $loan->is_allocated = 1;
                if(!empty($loan->user_id)) {
                    $originUser = User::find($loan->user_id);
                    if ($originUser && $originUser->org_code != $org->org_code) {
                        // 非当前部门
                        $loan->user_id = 0;
                    }
                }
                $loan->org_root = $org->org_root;
                $loan->org_code = $org->org_code;
            }
            if ($loan->save())  {
                $price_ticket = Internal::getNeedTicket($loan->category_type, $loan->province,$loan->id);
                $user->ticket -= $price_ticket;
                $user->save();
                ConsumeEvent::dispatch($user->id, -$price_ticket);

                AllocateEvent::dispatch($loan, $request->user(), $org ?? '', $user ?? '');
                $success++;
            }
        }

        return response()->json([
            'code' => 0,
            'msg' => sprintf("成功分派%d条数据", $success),
            'data' => null
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function detail(Request $request, $id)
    {
        $loan = LoanApplication::with(['org', 'user', 'creditProvident', 'mortgageCar', 'mortgageHouse', 'mortgageTax'])
            ->ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        } else {

            $tags = [];
            foreach ($loan->tags as $v) {
                $tags[] = [
                    'id' => $v->id,
                    'title' => $v->title,
                ];
            }
            $res = $loan->toArray();
            $zhima = "无";
            if($loan->zhima == 2){
                $zhima = '600分以下';
            }elseif ($loan->zhima == 3){
                $zhima = '600-650分';
            }elseif ($loan->zhima == 4){
                $zhima = '650-700分';
            }elseif ($loan->zhima == 5){
                $zhima = '大于700';
            }

            $res['zhima'] = $zhima;
            $res['refund_msg'] =  $loan->refund_msg;
            $res['has_house'] = $loan->has_house ?? '无';
            $res['has_car'] = $loan->has_car ?? '无';
            $res['has'] = $loan->has ?? '无';
            $res['yingyezhizhao'] = $loan->yingyezhizhao ?? '无';
            $res['has_gongjijin'] = $loan->has_gongjijin ?? '无';
            $res['tags'] = $tags;

            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => $res
            ]);
        }
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse|void
     */
    public function update(Request $request, $id) {
        $loan = LoanApplication::ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }
        $origin = $loan->toArray();


        if ($request->status) {
            $loan->status = (int) $request->status;
        }
        if ($request->status && (int) $request->status == 16 && !$origin['user_id']) {
            return response()->json([
                'code' => 1,
                'msg' => '该订单还未被抢',
                'data' => null
            ]);
        }


        if($loan->save()) {
            if ($request->status == 16) {
                    $ticket  = Internal::getNeedTicket($origin['category_type'], $origin['province'],$origin['id']);
                    $toUser = User::find($origin['user_id']);
                    $toUser->ticket += $ticket;
                    $toUser->save();
                    RefundEvent::dispatch($toUser->id, $ticket, sprintf("抢单退款 %s", $origin['name']));
            }
            UpdateEvent::dispatch($origin, $loan->toArray(), $request->user());

            $loan->load(['org', 'user', 'creditProvident', 'mortgageCar', 'mortgageHouse', 'mortgageTax']);
            return response()->json([
                'code' => 0,
                'msg' => '保存成功',
                'data' => $loan
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '保存失败',
                'data' => null
            ]);
        }

    }

    public function delete(Request $request, $id)
    {
        $loan = LoanApplication::where('id',$id)->delete();

        return response()->json([
            'code' => 0,
            'msg' => '删除成功',
            'data' => $loan
        ]);
    }




    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function log(Request $request, $id)
    {
        $pageSize = (int) $request->input('pageSize', 20);
        $loan = LoanApplication::ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => LoanApplicationLog::with("user")
                ->where('loan_id', $id)
                ->orderByDesc('id')->paginate($pageSize)
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function saveLog(Request $request, $id)
    {
        $loan = LoanApplication::ofOwner($request->user())->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }

        if(empty(trim($request->comment))) {
            return response()->json([
                'code' => 1,
                'msg' => '内容不能为空',
                'data' => null
            ]);
        }

        $loanLog = new LoanApplicationLog();
        $loanLog->comment = trim($request->comment);
        $loanLog->loan_id = $loan->id;
        $loanLog->user_id = $request->user()->id;
        $loanLog->org_root = $request->user()->org_root;
        $loanLog->org_code = $request->user()->org_code;

        if($loanLog->save()) {
            $loanLog->load('user');
            return response()->json([
                'code' => 0,
                'msg' => '保存成功',
                'data' => $loanLog
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '保存失败',
                'data' => null
            ]);
        }
    }


    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse|void
     */
    public function saveTag(Request $request, $id)
    {
        $user = $request->user();
        $loan = LoanApplication::where('user_id', $user->id)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }

        if (empty($request->tags)) {
            $detached = [];
            foreach ($loan->tags as $v) {
                $detached[] = $v->id;
            }
            $loan->tags()->detach();

            LoanTagEvent::dispatch($loan, $user, [], $detached);
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => null
            ]);
        }

        $tag_ids = [];
        foreach ($request->tags as $v) {
            $tag =  LoanTag::ofOwner($user)->find($v['id']);
            if (empty($tag)) {
                return response()->json([
                    'code' => 1,
                    'msg' => sprintf("没有标签权限: [%s]", $v['title']),
                    'data' => null
                ]);
            }

            $tag_ids[] = (int) $v['id'];
        }

        $changes = $loan->tags()->sync($tag_ids);

        LoanTagEvent::dispatch($loan, $user, $changes['attached'], $changes['detached']);

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => null
        ]);
    }


    public function saveRefund(Request $request, $id)
    {
        $loan = LoanApplication::find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        }
        $loan->refund_msg = $request->refund_msg;
        if($loan->save()) {
            return response()->json([
                'code' => 0,
                'msg' => '保存成功',
                'data' => null
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '保存失败',
                'data' => null
            ]);
        }
    }

}
